package myweb

import (
	"fmt"
	"main/getPortsList"
	"main/myInterface"
	"net/http"

	"github.com/gin-gonic/gin"
)

var (
	err error
)

func serialWeb(r *gin.Engine, ws string) {
	r.GET("/serial", func(c *gin.Context) {
		err = myInterface.SerialClose()
		c.HTML(http.StatusOK, "serial.html", gin.H{
			"ws": ws,
		})
	})
	r.POST("/portlist", func(c *gin.Context) {
		portlist := getPortsList.GetSerialPortName()
		c.IndentedJSON(200, portlist)
	})
	r.POST("/timingSend", func(c *gin.Context) {
		timingSend := c.PostForm("timingSend")
		fmt.Println(timingSend)
		c.JSON(200, gin.H{
			"message": "POST",
		})
	})

	r.POST("/OpenSerial", func(c *gin.Context) {
		data := c.PostForm("data")
		portName := c.PostForm("portName")
		fmt.Println(portName)
		if data == "open" {
			//打开串口
			err = myInterface.SerialInit(portName, 115200)
			if err != nil {
				fmt.Println("open err")
				c.JSON(200, gin.H{
					"message":   "POST",
					"serilOpen": "NG",
				})
			} else {
				fmt.Println("open")
				c.JSON(200, gin.H{
					"message":   "POST",
					"serilOpen": "OK",
				})
			}
		} else {
			//关闭串口
			err = myInterface.SerialClose()
			if err != nil {
				c.JSON(200, gin.H{
					"message":    "POST",
					"serilClose": "NG",
				})
			} else {
				c.JSON(200, gin.H{
					"message":    "POST",
					"serilClose": "OK",
				})
			}
		}
	})
}
